package com.plum.admin.common.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.exception.BaseException;
import com.plum.admin.common.vo.TokenUser;
import com.plum.admin.modules.sys.entity.SysUser;
import com.plum.admin.modules.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/8/13 16:58
 */
@Component
public class SecurityUtil {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 获取当前登录用户
     * @return
     */
    public SysUser getUser(){
        Authentication authentication=getAuthentication();
        return userService.findByUsername(authentication.getName());
    }

    /**
     * 获取用户名
     * @return
     */
    public String getUsername(){
        Authentication authentication=getAuthentication();
        return authentication.getName();
    }

    /**
     * 获取登录用户对象
     * @return
     */
    private Authentication getAuthentication(){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || authentication.getName() == null || authentication instanceof AnonymousAuthenticationToken) {
            throw new BaseException("未检测到登录用户");
        }
        return authentication;
    }

    /**
     * 获取登录的用户权限
     * @return
     */
    public List<String> getAuthorities(){
        Authentication authentication=getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> permissions= Lists.newArrayList();
        for (GrantedAuthority authority : authorities) {
            permissions.add(authority.getAuthority());
        }
        return permissions;
    }
    public String getToken(String username){
        if(StrUtil.isBlank(username)){
            throw new BaseException("用户名不能为空");
        }
        SysUser user = userService.findByUsername(username);
        TokenUser tokenUser = new TokenUser(username, new ArrayList<>(user.getPermissionList()));
        String oldToken = redisTemplate.opsForValue().get(Constant.USER_TOKEN + username);
        if(StrUtil.isNotBlank(oldToken)){
            redisTemplate.delete(Lists.newArrayList(Constant.USER_TOKEN + username,Constant.TOKEN_PRE+oldToken));
        }
        String token = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set(Constant.USER_TOKEN+username,token,5L, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(Constant.TOKEN_PRE+token,new Gson().toJson(tokenUser),5L, TimeUnit.DAYS);
        return token;
    }
}
